﻿using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Bookvar.UI
{
    public abstract class ShapeTopicConnector : TopicConnectorBase
    {
        private readonly Dictionary<int, Shape> shapesDictionary = new Dictionary<int, Shape>();

        protected abstract Shape GetShape( TopicContentPresenter parent, TopicContentPresenter child );

        public override void Connect( TopicContentPresenter parent, TopicContentPresenter child )
        {
            Shape shape = GetShape(parent, child);
            shape.Stroke = Brushes.Black;
            Panel.SetZIndex( shape, -1 );

            parent.Owner.Children.Add( shape );

            shapesDictionary.Add( GetKey( parent, child ), shape );
        }

        public override void Disconnect( TopicContentPresenter parent, TopicContentPresenter child )
        {
            int key = GetKey( parent, child );
            Shape shape;
            if ( shapesDictionary.TryGetValue( key, out shape ) )
            {
                parent.Owner.Children.Remove( shape );
                BindingOperations.ClearAllBindings( shape );
                shapesDictionary.Remove( key );
            }
        }

        private static int GetKey( TopicContentPresenter parent, TopicContentPresenter child )
        {
            return parent.Topic.GetHashCode() ^ child.Topic.GetHashCode();
        }
    }
}